import React, { useEffect, useState } from 'react';
import { Button, Badge, Tree, Modal, message } from 'antd';
import ProCard from '@ant-design/pro-card';
const confirm = Modal.confirm;
import './index.less';
import { PageContainer } from '@ant-design/pro-layout';
// @ts-ignore
import InsertFolder from './components/insertFolder';
import { FolderTwoTone, FolderOpenTwoTone } from '@ant-design/icons';
import { request, useAccess, Access } from 'umi';
import { api } from '@/global';
import InsertFile from './components/InsertFile';
const TreeNode = Tree.TreeNode;
import FileListComponent from './components/FileListComponent';
import InsertBucketComponent from './components/InsertBucketComponent';
type folderType = {
  bucketName: string;
  children: string;
  id: number;
  parent: number;
  pathCode: string;
  pathName: string;
  childrenList: folderType[];
};

const DocumentUpload: React.FC = () => {
  const [selectFolder, SetSelectFolder] = useState('');
  const [selectBucket, SetSelectBucket] = useState<any>();
  const [FolderInfo, SetFolderInfo] = useState({});
  const [expandFolder, SetExpandFolder] = useState<string[]>();
  const access = useAccess();
  const initData = async () => {
    const result = await request(api.getFolderList);
    SetFolderInfo(result.data);
  };
  const reloadData = () => {
    initData();
  };
  const generateBranch = (p: folderType) => {
    if (!p) {
      return;
    }

    const template = (
      <TreeNode
        style={{ width: '100%' }}
        title={(info: any) => {
          return (
            <div style={{ display: 'inline-block' }} key={p.pathCode}>
              <span>{p.pathName}</span>
              &nbsp;&nbsp;&nbsp;
              {selectFolder === info.key && (
                <Access
                  key={'delete' + p.id}
                  accessible={access.normalButtonFilter('FILEFOLAD:DELETE')}
                >
                  <a
                    key={p.pathCode}
                    onClick={() => {
                      confirm({
                        title: `是否确认删除文件夹`,
                        content: '文件夹下不许有文件存在，请仔细确认',
                        okText: 'Yes',
                        okType: 'danger',
                        cancelText: 'No',

                        onOk: async () => {
                          const result = await request(api.deleteFileFolder, {
                            method: 'POST',
                            data: {
                              id: selectFolder,
                            },
                          });
                          if (result.success) {
                            reloadData();
                            message.info('删除成功');
                          }
                        },
                        onCancel: () => {},
                      });
                    }}
                  >
                    删除
                  </a>
                </Access>
              )}
            </div>
          );
        }}
        key={p.pathCode}
        icon={() => {
          const isExpand = expandFolder?.includes(p.pathCode);
          let temp = <FolderTwoTone />;
          if (isExpand) {
            temp = <FolderOpenTwoTone />;
          }

          return temp;
        }}
      >
        {p.childrenList &&
          p?.childrenList.map((a: folderType) => {
            return generateBranch(a);
          })}
      </TreeNode>
    );

    return template;
  };

  const onSelect = (selectedKeys: any[], _) => {
    if (selectedKeys.length == 1) {
      const p = selectedKeys[0];
      if (p.charAt(p.length - 1) != '/') {
        SetSelectBucket(p);
        SetSelectFolder('');
      } else {
        SetSelectFolder(selectedKeys[0]);
      }
    } else {
      SetSelectBucket('');
      SetSelectFolder('');
    }
  };
  const onExpand = (expanded: string[], _) => {
    SetExpandFolder(expanded);
  };

  const reloadfile = (foo: any) => {
    foo();
  };

  useEffect(() => {
    initData();
  }, []);

  return (
    <PageContainer
      header={{
        title: '文件上传',
        breadcrumb: {
          routes: [
            {
              path: '',
              breadcrumbName: '文件综合管理',
            },
            {
              path: '',
              breadcrumbName: '文件上传',
            },
          ],
        },
      }}
    >
      <ProCard split="vertical">
        <ProCard
          title="文件列表"
          headerBordered
          colSpan="365px"
          key={'folder'}
          extra={[
            <Access key="InsertFolder" accessible={access.normalButtonFilter('FILEFOLAD:INSERT')}>
              <InsertFolder key="InsertFolder" reloadData={reloadData} />
            </Access>,
            <Access key="InsertBucket" accessible={access.normalButtonFilter('FILEFOLAD:INSERT')}>
              <InsertBucketComponent key="InsertBucket" reloadData={reloadData} />
            </Access>,
          ]}
        >
          <div>
            <Tree
              defaultExpandAll
              onSelect={onSelect}
              style={{ fontSize: '17px' }}
              showIcon={true}
              onExpand={onExpand}
            >
              {FolderInfo &&
                Object.keys(FolderInfo).map((item) => {
                  const data = FolderInfo[item];

                  const result = (
                    <TreeNode title={item} key={item}>
                      {data.map((folder: folderType) => {
                        return generateBranch(folder);
                      })}
                    </TreeNode>
                  );

                  return result;
                })}
            </Tree>
          </div>
        </ProCard>

        <FileListComponent selectFolder={selectFolder} selectBucket={selectBucket} />
      </ProCard>
    </PageContainer>
  );
};

export default DocumentUpload;
